package com.demo.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.demo.aop.AuthorizationRequired;
import com.demo.core.constants.HttpStatus;
import com.demo.core.domain.Result;
import com.demo.core.exception.ParameterException;
import com.demo.domain.PracticeProject;
import com.demo.domain.ro.GetProjectRequest;
import com.demo.domain.ro.SearchPracticeProject;
import com.demo.service.PracticeProjectService;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/project")
@CrossOrigin
public class PracticeProjectController {
    @Autowired
    private PracticeProjectService practiceProjectService;

    /**
     * 搜索赛事名
     *
     * @param kw
     * @param request
     * @return
     * @throws Exception
     */
    @AuthorizationRequired
    @Operation(summary = "搜索赛事名", description = "模糊查询，需登录")
    @PostMapping("/getProjectNameList")
    public Result getProjectByName(String kw, HttpServletRequest request) throws Exception {
        if (request == null) {
            throw new ParameterException("request为空");
        }
        Long uid = (Long) request.getAttribute("userId");
        List<String> list = practiceProjectService.getProjectsByName(kw, uid);
        return list != null && list.size() > 0 ?
                Result.success(HttpStatus.SUCCESS, "查找成功", list) :
                Result.success(HttpStatus.SUCCESS, "无相关信息", new ArrayList<>());
    }

    /**
     * 得到全部的比赛，有分页（用在首页）
     *
     * @param current
     * @param size
     * @return
     */
    @AuthorizationRequired
    @Operation(summary = "得到所有赛事信息", description = "根据分页信息")
    @RequestMapping("/getAllProject")
    @CrossOrigin
    public Result getAll(int current, int size, HttpServletRequest request) throws ParameterException, Exception {
        if (current <= 0 || size <= 0) {
            throw new ParameterException("分页信息无效");
        }
        if (request == null) {
            throw new ParameterException("request为空");
        }
        Long uid = (Long) request.getAttribute("userId");
        if (uid == null || uid < 0l) {
            throw new ParameterException("未登录");
        }
        IPage page = practiceProjectService.getAllProjectsByPage(current, size);
        return page.getRecords().size() == 0 ?
                Result.success(HttpStatus.SUCCESS, "无相关信息", new Page<>())
                : Result.success(HttpStatus.SUCCESS, "查找成功", page);
    }

    /**
     * 根据某个字段进行竞赛搜索，有分页
     *
     * @param
     * @return
     */
    @AuthorizationRequired
    @Operation(summary = "搜索赛事信息", description = "根据搜索字段(年级、关键词、指导老师、类别其中一个)、关键词、分页信息")
    @PostMapping("getProjectByKW")
    @CrossOrigin
    public Result getByKW(@RequestBody GetProjectRequest getProjectRequest, HttpServletRequest request) throws ParameterException {
        if (getProjectRequest == null) {
            throw new ParameterException("getProjectRequest为空");
        }
        if (request == null) {
            throw new ParameterException("request为空");
        }
        Long uid = (Long) request.getAttribute("userId");
        if (uid == null || uid < 0l) {
            throw new ParameterException("未登录");
        }
        String type = getProjectRequest.getType();
        String kw = getProjectRequest.getKw();
        int current = getProjectRequest.getCurrent();
        int size = getProjectRequest.getSize();
        if (current <= 0 || size <= 0) {
            throw new ParameterException("分页信息无效");
        }
        Page<PracticeProject> page = practiceProjectService.getProjectByKey(type, kw, current, size);
        return page.getRecords().size() == 0 ?
                Result.success(HttpStatus.SUCCESS, "无相关信息", new Page<>()) :
                Result.success(HttpStatus.SUCCESS, "查找成功", page);
    }

    /**
     * 根据项目名得到某个项目的完整信息（项目名要完整，未实现模糊查询）
     *
     * @param name
     * @return
     */
    @AuthorizationRequired
    @Operation(summary = "得到某个赛事的详情信息", description = "根据赛事的完整名称")
    @RequestMapping("/getProjectDetailByName")
    public Result getProjectDetailByName(String name, HttpServletRequest request) throws ParameterException, Exception {
        if (name == null || name.equals("")) {
            throw new ParameterException("参数name为空");
        }
        if (request == null) {
            throw new ParameterException("request为空");
        }
        Long uid = (Long) request.getAttribute("userId");
        if (uid == null || uid < 0l) {
            throw new ParameterException("未登录");
        }
        PracticeProject pp = practiceProjectService.getProjectDetailByName(name);
        return pp == null ? Result.success(HttpStatus.BAD_REQUEST, "无相关信息", null) :
                Result.success(HttpStatus.SUCCESS, "查找成功", pp);
    }


    /**
     * 数据的CRUD
     */


    /**
     * 搜索竞赛
     *
     * @param searchPP
     * @param request
     * @return
     * @throws ParameterException
     */
    @AuthorizationRequired
    @Operation(summary = "搜索竞赛")
    @RequestMapping("/pp/search")
    public Result searchPracticeProject(@RequestBody SearchPracticeProject searchPP, HttpServletRequest request) throws Exception {
        if (searchPP == null) {
            throw new ParameterException("searchPP为空");
        }
        if (request == null) {
            throw new ParameterException("request为空");
        }
        Long uid = (Long) request.getAttribute("userId");
        if (uid == null) {
            throw new ParameterException("未登录");
        }
        int current = searchPP.getCurrent();
        int size = searchPP.getSize();
        Page<PracticeProject> page = new Page<>(current, size);
        //查询
        LambdaQueryWrapper<PracticeProject> wrapper = practiceProjectService.searchPracticeProject(searchPP.getPpName(), searchPP.getPpSuitableStudent(), searchPP.getPpCategory());
        practiceProjectService.page(page, wrapper);
        return Result.success(HttpStatus.SUCCESS, "查找成功", page);
    }

    /**
     * 得到某个竞赛
     *
     * @param ppId
     * @param request
     * @return
     * @throws ParameterException
     */
    @AuthorizationRequired
    @Operation(summary = "得到某个竞赛")
    @RequestMapping("/pp/get")
    public Result getPracticeProjectById(Long ppId, HttpServletRequest request) throws ParameterException {
        if (ppId == null || ppId < 1l) {
            throw new ParameterException("ppId为空");
        }
        if (request == null) {
            throw new ParameterException("request为空");
        }
        Long uid = (Long) request.getAttribute("userId");
        if (uid == null) {
            throw new ParameterException("未登录");
        }
        PracticeProject pp = practiceProjectService.getById(ppId);
        return Result.success(HttpStatus.SUCCESS, "查找成功", pp.getPpIsDelete() == 0 ? pp : null);
    }


    /**
     * 新增竞赛
     *
     * @param pp
     * @param request
     * @return
     * @throws ParameterException
     */
    @AuthorizationRequired
    @Operation(summary = "新增竞赛")
    @RequestMapping("/pp/add")
    @Transactional(rollbackFor = Exception.class)
    public Result addPracticeProject(@RequestBody PracticeProject pp, HttpServletRequest request) throws ParameterException {
        if (pp == null) {
            throw new ParameterException("无新增事项");
        }
        if (request == null) {
            throw new ParameterException("request为空");
        }
        Long uid = (Long) request.getAttribute("userId");
        if (uid == null) {
            throw new ParameterException("未登录");
        }
        if (pp.getPpName() == null || pp.getPpName().isEmpty() || pp.getPpCategory() == null || pp.getPpCategory().isEmpty()) {
            throw new ParameterException("信息未填写完整");
        }
        pp.setPpId(null);
        pp.setPpIsDelete(null);
        return Result.success(HttpStatus.SUCCESS, "新增成功", practiceProjectService.save(pp));
    }

    /**
     * 修改某个竞赛
     *
     * @param pp
     * @param request
     * @return
     * @throws ParameterException
     */
    @AuthorizationRequired
    @Operation(summary = "修改某个竞赛")
    @RequestMapping("/pp/update")
    public Result updatePracticeProjectById(@RequestBody PracticeProject pp, HttpServletRequest request) throws ParameterException {
        if (pp == null) {
            throw new ParameterException("scientificDirection为空");
        }
        if (request == null) {
            throw new ParameterException("request为空");
        }
        Long uid = (Long) request.getAttribute("userId");
        if (uid == null) {
            throw new ParameterException("未登录");
        }
        if (pp.getPpId() == null || pp.getPpId() < 1l) {
            throw new ParameterException("PracticeProject Id错误");
        }
        return Result.success(HttpStatus.SUCCESS, "修改成功", practiceProjectService.updateById(pp));
    }


    /**
     * 删除竞赛
     *
     * @param ppIds
     * @param request
     * @return
     * @throws ParameterException
     */
    @AuthorizationRequired
    @Operation(summary = "删除竞赛")
    @RequestMapping("/pp/delete")
    @Transactional(rollbackFor = Exception.class)
    public Result deletePracticeProject(@RequestBody List<Long> ppIds, HttpServletRequest request) throws ParameterException {
        if (ppIds == null || ppIds.size() < 1) {
            throw new ParameterException("无删除事项");
        }
        if (request == null) {
            throw new ParameterException("request为空");
        }
        Long uid = (Long) request.getAttribute("userId");
        if (uid == null) {
            throw new ParameterException("未登录");
        }
        List<PracticeProject> practiceProjects = new ArrayList<>();
        for (Long id : ppIds) {
            if (id != null && id > 0l) {
                PracticeProject project = new PracticeProject();
                project.setPpId(id);
                project.setPpIsDelete(1);//1已删除
                practiceProjects.add(project);
            }
        }
        return Result.success(HttpStatus.SUCCESS, "删除成功", practiceProjectService.updateBatchById(practiceProjects));
    }


}
